<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import TreeUtilDTO from '@/utils/tree'
import { useRoute } from 'vue-router'
import wsjzglService from '@/api/wsjzgl'
import { getFldm } from '@/utils/get-fldm'
const route = useRoute()
// 入参

const form = ref({
  gjz: '',
  xgfsdm: '',
  xgfsmc: '',
  xgzddm: '',
  xgzdmc: '',
  radioCurrent: '',
})

// 生命周期
onMounted(() => {
  //
})

const defaultProps = {
  children: 'children',
  label: 'mc',
}

const firtsNode = ref<any>()

/*
 * 树节点点击（抛出方法到主界面）
 */
const treeNodeData = ref()
const treeNodeClick = (data: any) => {
  treeNodeData.value = data
  form.value.gjz = ''
  queryForm.value = {
    tcnrValue: '',
    cznrValue: '',
    thnrValue: '',
    dqzjValue: '',
    dhzjValue: '',
  }
  getPlxgjl()
}

/**
 * 树节点过滤
 */
const filtersNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

/*
 * 查询案卷目录
 */
const treeData = ref<any[]>([])
const queryAjml = () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: '0',
  }
  wsjzglService
    .queryAjmls(params)
    .then((res) => {
      let obj = route.query
      res.data?.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbh: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: obj.ajsl,
      })
      let newArr = res.data.filter((item: any) => {
        return item.mc !== '待编目材料'
      })
      treeData.value = TreeUtilDTO.getTreeData(newArr, 'bh', 'fbh')
      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) return
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

const handleCheckNode = (node: any) => {
  treeNodeClick(node)
  nextTick(() => {
    treeRef.value!.setCurrentKey(node.bh)
  })
}

// 获取批量修改记录
const llxgjlData = ref()
const getPlxgjl = () => {
  const params = {
    mlbh: treeNodeData.value?.bh,
  }
  wsjzglService
    .getPlxgjl(params)
    .then((res) => {
      llxgjlData.value = res.data
      queryForm.value.tcnrValue = res.data?.tcnr
      queryForm.value.cznrValue = res.data?.ccnr
      queryForm.value.thnrValue = res.data?.thnr
      queryForm.value.dqzjValue = res.data?.dqzj
      queryForm.value.dhzjValue = res.data?.dhzj
      form.value.xgfsdm = res.data?.xgfsdm
      form.value.xgfsmc = res.data?.xgfsmc
      form.value.xgzddm = res.data?.xgzddm
      form.value.xgzdmc = res.data?.xgzdmc
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
/*
 * 树节点渲染
 */
const treeNodeRender = () => {
  //
}

/*
 * 树节点勾选
 */
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeNodeCheck = () => {
  const nodes = treeRef.value?.getCheckedNodes() as any
  // checkNodes.value = nodes || []
}

/*
 * 生成目录
 */
const createZzml = () => {
  const params = {}
  // wsjzglService
  //   .createZzml(params)
  //   .then((res) => {
  //     //
  //   })
  //   .catch((err) => {
  //     !err.isError && ElMessage({ type: 'warning', message: err.message })
  //   })
}

const dialogVisible = ref(false)
/*
 * 打开弹框
 */
const openDialog = () => {
  // 查询案卷目录
  queryAjml()
  // // 获取皮批量修改记录
  // getPlxgjl()
  // 批量修改字段分类代码
  getXgzd()
  // 批量修改字段方式分类代码
  getXgfs()
  dialogVisible.value = true
}

// 批量修改字段分类代码
const xgzdList = ref<any>([])
const getXgzd = async () => {
  xgzdList.value = await getFldm('gd039')
}

const xgfsList = ref<any[]>([])
const getXgfs = async () => {
  xgfsList.value = await getFldm('gd040')
}

// 修改字段change
const xgzdChange = (index: number) => {
  form.value.xgzdmc = xgzdList.value[index].mc
  form.value.xgzddm = xgzdList.value[index].dm
}

// 修改方式change
const xgfsChange = (val: string) => {
  queryForm.value.tcnrValue = ''
  queryForm.value.cznrValue = ''
  queryForm.value.thnrValue = ''
  queryForm.value.dqzjValue = ''
  queryForm.value.dhzjValue = ''
  let obj: any = {}
  obj = xgfsList.value.find((item: any) => {
    return item.dm === val //筛选出匹配数据，这里的value是你遍历数组每一项的value，如果没有对后台返回的数据做处理，一般为id
  })
  form.value.xgfsdm = obj.dm
  form.value.xgfsmc = obj.mc
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  dialogVisible.value = false
}

/*
 * 保存（成功抛出刷新）
 */
const save = () => {
  if (!nodeValue.value.length) return ElMessage({ type: 'error', message: '请勾选目录' })
  if (!form.value.xgzddm) return ElMessage({ type: 'error', message: '请选择修改字段' })
  if (!form.value.xgfsdm) return ElMessage({ type: 'error', message: '请选择修改方式' })
  const params = {
    ccnr: queryForm.value.cznrValue ? queryForm.value.cznrValue : llxgjlData.value?.ccnr,
    dhzj: queryForm.value.dhzjValue,
    dqzj: queryForm.value.dqzjValue,
    list: nodeValue.value.map((item: any) => {
      return {
        ajbh: item.ajbh,
        mlbh: item.bh,
        jlbh: llxgjlData.value?.jlbh || '',
      }
    }),
    tcnr: queryForm.value.tcnrValue ? queryForm.value.tcnrValue : llxgjlData.value?.tcnr,
    thnr: queryForm.value.thnrValue ? queryForm.value.thnrValue : llxgjlData.value?.thnr,
    xgfsdm: form.value.xgfsdm ? form.value.xgfsdm : llxgjlData.value.xgfsdm,
    xgfsmc: form.value.xgfsmc ? form.value.xgfsmc : llxgjlData.value.xgfsmc,
    xgzddm: form.value.xgzddm ? form.value.xgzddm : llxgjlData.value.xgzddm,
    xgzdmc: form.value.xgzdmc ? form.value.xgzdmc : llxgjlData.value.xgzdmc,
  }
  dialogVisible.value = false
  wsjzglService
    .savePlxgjl(params, route.query.ajbh as string)
    .then(() => {
      ElMessage({ type: 'success', message: '保存成功' })
      nodeValue.value = []
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 文字过滤
const filtersTree = () => {
  treeRef.value?.filter(form.value.gjz)
}

// 单选框
const radioCurrent = ref()
// 填充内容
const queryForm = ref({
  tcnrValue: '',
  cznrValue: '',
  thnrValue: '',
  dqzjValue: '',
  dhzjValue: '',
})

const nodeValue = ref([])
const checkChange = (data: any, nonde: any) => {
  const node = nonde.checkedNodes
  nodeValue.value = node.filter((item: any) => item.cj === '2')
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量修改"
    width="1100px"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <div class="dialog-content">
      <div class="left-tree">
        <el-tabs class="demo-tabs" type="card">
          <el-tab-pane label="案卷">
            <div class="left-content">
              <header class="dialog-header">
                <el-input
                  v-model="form.gjz"
                  autosize=""
                  placeholder="请输入查询关键字"
                  suffix-icon="Search"
                  @change="filtersTree"
                />
              </header>
              <div class="tree-box">
                <el-tree
                  ref="treeRef"
                  style="max-width: 600px"
                  :data="treeData"
                  show-checkbox
                  draggable
                  node-key="bh"
                  highlight-current
                  default-expand-all
                  :expand-on-click-node="false"
                  :props="defaultProps"
                  @node-click="treeNodeClick"
                  @check="checkChange"
                  :filter-node-method="filtersNode"
                >
                  <template #default="{ data }">
                    <span class="custom-tree-node">
                      <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" />
                      <img v-if="data.cj === '1'" src="/src/assets/images/text-icon.png" alt="" />
                      <img v-if="data.cj === '2'" src="/src/assets/images/ellipse.png" alt="" />
                      <span
                        >&nbsp;
                        {{ data.mc }}
                      </span>
                    </span>
                  </template>
                </el-tree>
                <!-- <el-tree
                  ref="treeRef"
                  node-key="mlbh"
                  :data="treeData"
                  :props="defaultProps"
                  show-checkbox
                  check-strictly
                  default-expand-all
                  highlight-current
                  :filter-node-method="treeNodeFilter"
                  @check-change="treeNodeCheck"
                /> -->
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="right-edit">
        <div class="edit-item">
          <span>修改字段:</span>
          <el-select
            v-model="form.xgzdmc"
            clearable
            placeholder="请选择"
            style="width: 100%"
            @change="xgzdChange"
          >
            <el-option
              v-for="(zrritem, index) in xgzdList"
              :key="zrritem.dm"
              :label="zrritem.mc"
              :value="index"
            >
            </el-option>
          </el-select>
        </div>
        <div class="edit-item edite-radio">
          <span class="edit-title">修改方式:</span>
          <el-radio-group v-model="form.xgfsdm" class="ml-4" @change="xgfsChange">
            <el-radio
              v-for="zrritem in xgfsList"
              :key="zrritem.dm"
              :value="zrritem.dm"
              :label="zrritem.mc"
            ></el-radio>
          </el-radio-group>
        </div>

        <div class="edit-item" v-if="form.xgfsdm === 'gd0400001'">
          <span>填充内容:</span>
          <el-input v-model="queryForm.tcnrValue" maxlength="30"></el-input>
        </div>

        <template v-if="form.xgfsdm === 'gd0400002'">
          <div class="edit-item">
            <span>查找内容:</span>
            <el-input v-model="queryForm.cznrValue" maxlength="30"></el-input>
          </div>
          <div class="edit-item">
            <span>替换内容:</span>
            <el-input v-model="queryForm.thnrValue" maxlength="30"></el-input>
          </div>
        </template>

        <template v-if="form.xgfsdm === 'gd0400003'">
          <div class="edit-item">
            <span>段前追加:</span>
            <el-input v-model="queryForm.dqzjValue" maxlength="30"></el-input>
          </div>
          <div class="edit-item">
            <span>段后追加:</span>
            <el-input v-model="queryForm.dhzjValue" maxlength="30"></el-input>
          </div>
        </template>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-content {
  width: 100%;
  height: 500px;
  display: flex;

  .left-tree {
    width: 50%;

    .left-content {
      display: flex;
      flex-direction: column;
      height: 100%;

      .dialog-header {
        height: 40px;
      }

      .tree-box {
        flex: 1;
        flex-shrink: 0;
        overflow: auto;
      }
    }
  }

  .right-edit {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 30px;

    .edit-item {
      display: flex;
      align-items: center;
      & > span {
        display: block;
        width: 100px;
      }
    }

    .edit-item + .edit-item {
      margin-top: 15px;
    }

    .edite-radio {
      align-items: stretch;
    }
  }
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-input-border-color) !important;
}

:deep(.el-select__wrapper) {
  box-shadow: 0 0 0 1px var(--el-border-color) !important;
}

:deep(.el-radio) {
  display: block;
  width: 50%;
}
</style>
